package my.suveng.sharding.algorithm;

import java.util.Collection;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import my.suveng.sharding.config.DataSourceConfigProperties;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * 单一分片键
 * @author suwenguang
 * @date 2020/11/3 4:50 下午
 * @since 1.0
 */
@Slf4j
@Configuration
public class IdPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

	@Autowired
	DataSourceConfigProperties dataSourceConfigProperties;

	/**
	 * 单分片键 分片算法
	 * 实现: 一致性hash + 权重 + 版本标记
	 */
	@Override
	public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
		String key = preciseShardingValue.getValue();
		// 获取id版本号
		String versionKey = StrUtil.sub(key, 0, 4);
		// 获取路由版本
		DataSourceRoute dataSourceRoute = DataSourceRoute.get(versionKey);
		// 路由数据源
		return dataSourceRoute.route(key);
	}
}
